<template>
  <div>
    <el-button type="text" @click="dialogFormVisible = true" class="left"
      >添加</el-button
    >

    <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="角色名" :label-width="formLabelWidth">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="roleId" label="编号" width="180">
      </el-table-column>
      <el-table-column prop="roleName" label="角色名" width="180">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="del(scope.row)">删除</el-button>
          <el-button @click="updateUI(scope.row)">修改</el-button>
          <el-button @click="distributePermissionUI(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from "@/util/request.js";

export default {

  mounted() {
    this.getList();
  },
  methods: {
    distributePermissionUI(row) {
      this.$router.push(`/System/DistributePermission/${row.roleId}`);
    },
    getList() {
      axios.post("role/findAll").then((r) => {
        this.tableData = r.data;
      });
    },
    del(row) {
      this.$confirm("确认删除?")
        .then(() => {
          let roleId = row.roleId;
          let config = {
            headers: {
              "Content-Type": "text/plain",
            },
          };
          axios.post("role/delete/", roleId, config).then(r => {
            if (r.code == 200) {
              this.$message.success("删除成功");
              this.getList();
              return;
            }
            this.$message.error(r.msg);
          });
        })
        .catch(() => {});
    },
    submitForm() {
      let path = !this.form.roleId ? "save" : "update"
      axios.post(`role/${path}`, this.form).then( r => {
        if(r.code == 200) {
          this.$message.success(r.msg);
          this.dialogFormVisible = false;
          this.getList();
          this.form = {};
        }
      })
    },
    updateUI(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogFormVisible = true;
    },
  },
  data() {
    return {
      tableData: [],
      form: {},
      dialogFormVisible: false,
      formLabelWidth: "180px"
    };
  },
};
</script>

<style>
</style>